<template>
  <x-layout-main>
    <div class="g-content">
      <div>
        <x-button type="primary" @click="handleCreate">批量新建</x-button>
      </div>
    </div>
    <div class="g-content">
      <x-form
        ref="formRef"
        v-model:model="form"
        inline
        label-placement="left"
        :show-feedback="false"
        style="margin-bottom: 10px"
      >
        <n-grid cols="1 s:2 m:3 l:3 xl:4" responsive="screen" x-gap="16" y-gap="10">
          <n-form-item-gi path="orderNo" label="创建时间">
            <n-date-picker
              v-model:formatted-value="form.dateRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              clearable
              start-placeholder="创建开始日期"
              @update:value="handleSubmit"
            />
          </n-form-item-gi>
          <n-form-item-gi path="accountCode" label="账户ID">
            <n-input v-model:value="form.accountCode" placeholder="请输入账户ID" clearable />
          </n-form-item-gi>
          <n-form-item-gi>
            <x-button attr-type="submit" type="primary" icon="icon-076" @click="handleSubmit"> 搜索 </x-button>
            <x-button icon="icon-074" @click="handleReset"> 重置 </x-button>
          </n-form-item-gi>
        </n-grid>
      </x-form>
      <n-text type="error">批量操作记录最多保存一年，超出将自动清除</n-text>
      <div>
        <x-data-table
          ref="tableRef"
          v-model:immediate="immediate"
          :params="paginationParams"
          :columns="columns"
          :scroll-x="TableScrollX"
          :row-key="(row) => row.id"
          row-class-name="text-sm"
          max-height="infinite"
          @update:sorter="handleSorterChange"
        />
      </div>
    </div>
  </x-layout-main>
</template>
<script setup lang="ts">
  import { XLayoutMain, XForm, XButton, XDataTable } from '@/components'
  import { NGrid, NFormItemGi, NDatePicker, NInput, NText, NSpace, NTag, NPopconfirm } from 'naive-ui'
  import { computed, h, ref, VNode } from 'vue'
  import { useRouter } from 'vue-router'
  import { useStore } from '@/store'
  const router = useRouter()
  const store = useStore()
  const form = ref({
    accountCode: null,
    dateRange: null
  })
  const formRef = ref(null)

  const immediate = ref(true)
  const paginationParams = computed(() => {
    return {
      actions: 'intelligent/adgroupBatchList',
      data: {
        ...form.value,
        dateRange: null,
        startDate: form.value.dateRange?.[0],
        endDate: form.value.dateRange?.[1]
      }
    }
  })
  const columns = computed(() => {
    return [
      {
        title: '批次ID',
        key: 'batchId',
        width: 200
      },
      {
        title: '创建时间',
        key: 'createdAt',
        width: 200
      },
      {
        title: '账户ID',
        key: 'accountCodes',
        width: 300,
        render(row: any): VNode {
          const list = row.accountCodes.split(',')
          const t: VNode<RendererNode, RendererElement, { [key: string]: any }>[] = []
          list.forEach((item: any) => {
            t.push(h(NTag, { type: 'primary' }, () => item))
          })
          return h(NSpace, {}, () => t)
        }
      },
      {
        title: '提交人员',
        key: 'creatorName',
        width: 100
      },
      {
        title: '操作',
        width: 180,
        fixed: 'right',
        render(row: any) {
          return h(NSpace, {}, () => [
            h(XButton, { type: 'primary', text: true, onClick: () => handleUpload(row) }, () => '引用'),
            h(
              NPopconfirm,
              { onPositiveClick: () => handleDelete(row) },
              {
                default: () => '是否删除？',
                trigger: () => h(XButton, { type: 'primary', text: true }, () => '删除')
              }
            )
          ])
        }
      }
    ]
  })
  const TableScrollX = computed(() => {
    let x = 20
    columns.value.forEach((item) => {
      if (item.type === 'expand') {
        x += 30
      }
      if (item.type === 'selection') {
        x += 30
      }
      if (item.width) {
        x += item.width
      }
    })
    return x
  })

  function handleSorterChange(options: { order: string | number | boolean; columnKey: string }) {
    const sortKey: any = {
      descend: 'desc',
      ascend: 'asc'
    }
    form.value.order = options?.columnKey
    form.value.desc = options.order ? sortKey[options.order] : null
    handleSubmit()
  }

  const handleSubmit = () => {
    immediate.value = true
  }
  const handleReset = () => {
    formRef.value.resetFields()
    handleSubmit()
  }
  const handleCreate = () => {
    router.push({
      name: 'AdsCreate'
    })
  }
  const handleUpload = (row: any) => {
    router.push({
      name: 'IntelCreateList',
      query: {
        batchId: row.batchId
      }
    })
  }
  const handleDelete = async (row: any) => {
    console.log('shanchu')
    await store.dispatch('intelligent/adgroupBatchDelete', {
      batchId: row.batchId
    })
    handleSubmit()
  }
</script>

<style scoped lang="scss"></style>
